package com.sophon.pattern.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import com.sophon.pattern.proxy.remote.RemoteInterface;

public class DynamicProxy {

	public void doSomething() throws RemoteException, MalformedURLException, NotBoundException {
		RemoteInterface face = (RemoteInterface) Naming.lookup("rmi://localhost:8888/doSomething");
//		face.doSomething();
		RemoteInterface i = (RemoteInterface) Proxy.newProxyInstance(face.getClass().getClassLoader(), face.getClass().getInterfaces(),
				new InvocationHandler() {

					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						System.out.println("我是代理，读取公用代码，比如事务开始");
						System.out.println("调用被代理方法");
//						RemoteInterface face = (RemoteInterface) Naming.lookup("rmi://localhost:8888/doSomething");
						method.invoke(face, args);
						System.out.println("我是代理，读取公用代码，比如事务结束");
						return null;
					}
				});
		i.doSomething();
	}
}
